#!/bin/bash
#Description install redis-4.0.8
#date 2018/02/26
SOFTDIR=/usr/local/src
REDISVERSION=4.0.8
REDISPATH=/usr/local/redis-${REDISVERSION}
BINDIP=$(/sbin/ifconfig eth1|grep inet|grep -v inet6|awk '{print $2}')
REDISLOGDIR=/var/log/redis
REDISCONFDIR=/etc/redis
PROT=6379
REDISCONFNAME=redis_${PROT}.conf
REDISDBDIR=/var/lib/redis_${PROT}
USER=redis
GROUP=redis
# create redis user
if ! id $USER &>/dev/null;then
        groupadd -g 1211 $GROUP
        useradd -u 1211 -g $GROUP -s /sbin/nologin $USER
fi
#create redis log dir and redis RDB dbdir
[ ! -d $REDISLOGDIR ] && mkdir -p $REDISLOGDIR
[ ! -d $REDISDBDIR ] && mkdir -p $REDISDBDIR
chown -R $USER:$GROUP ${REDISLOGDIR}
chown -R $USER:$GROUP ${REDISDBDIR}
#install jemalloc
yum -y install jemalloc

#download redis and install redis
cd $SOFTDIR && [ ! -f redis-${REDISVERSION}.tar.gz ] && wget http://download.redis.io/releases/redis-4.0.8.tar.gz
[ ! -d redis-${REDISVERSION} ] && tar xf redis-${REDISVERSION}.tar.gz
cd redis-${REDISVERSION} && make PREFIX=${REDISPATH} install

#copy redis configure file redis
[ ! -d $REDISCONFDIR ] && mkdir -p $REDISCONFDIR
cd ${REDISCONFDIR} && [ ! -f ${REDISCONFNAME} ] && cd ${SOFTDIR}/redis-${REDISVERSION}  && cp redis.conf ${REDISCONFDIR}/${REDISCONFNAME}
sed -i "s#bind 127.0.0.1#bind ${BINDIP}#g" ${REDISCONFDIR}/${REDISCONFNAME}
sed -i "s#daemonize no#daemonize yes#g" ${REDISCONFDIR}/${REDISCONFNAME}
sed -i "s#logfile ""#logfile ${REDISLOGDIR}/redis_${PROT}.log#g" ${REDISCONFDIR}/${REDISCONFNAME}
sed -i "s#dir ./#dir ${REDISDBDIR}#g" ${REDISCONFDIR}/${REDISCONFNAME}
sed -i "500 a\ requirepass Aa123456" ${REDISCONFDIR}/${REDISCONFNAME}

#configure redis start script
cd ${SOFTDIR}/redis-${REDISVERSION}/utils && cp redis_init_script /etc/init.d/redis
sed -i '6 a \PROG=$(basename $0)' /etc/init.d/redis
sed -i 's#EXEC=/usr/local/bin/redis-server#EXEC=/usr/local/redis-4.0.8/bin/redis-server#g' /etc/init.d/redis
sed -i 's#CLIEXEC=/usr/local/bin/redis-cli#CLIEXEC=/usr/local/redis-4.0.8/bin/redis-cli#g' /etc/init.d/redis
sed -i 's#CONF="/etc/redis/${REDISPORT}.conf"#CONF="/etc/redis/redis_${REDISPORT}.conf"#g' /etc/init.d/redis
chmod u+x /etc/init.d/redis

#start redis start

/etc/init.d/redis start 

if [ "`ss -tunlp|grep 6379 |awk -F ":" '{print $2}'|awk '{print $1}'`" == "6379" ];then
	echo "redis start succefull"
else
	echo "redis start fail"
fi
echo "export PATH=${REDISPATH}/bin:$PATH" >> /etc/profile
source /etc/profile


#shutdown redis 
# vim /etc/init.d/redis  
# $CLIEXEC -p $REDISPORT -h ${BINDIP} shutdown

